<template>
  <div class="login-container">
    <el-card class="login-card">
      <div class="login-header">
        <h2>用户登录</h2>
      </div>
      <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="auto" class="login-form"
        @keyup.enter.prevent="handleKeyEnter">
        <el-form-item label="账号" prop="UserName">
          <el-input v-model="ruleForm.UserName" placeholder="请输入用户账号" prefix-icon="User"
            @keyup.enter="handleKeyEnter" />
        </el-form-item>
        <el-form-item label="密码" prop="UserPwd">
          <el-input v-model="ruleForm.UserPwd" show-password placeholder="请输入用户密码" prefix-icon="Lock"
            @keyup.enter="handleKeyEnter" />
        </el-form-item>
        <el-form-item label="记住密码" prop="IsRemember">
          <el-switch v-model="ruleForm.IsRemember" class="ml-2" inline-prompt
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" active-text="记住密码"
            inactive-text="忘记密码" />
        </el-form-item>
        <el-form-item>
          <div class="button-container">
            <el-button type="primary" @click="submitForm(ruleFormRef)" :loading="isLoading" :disabled="isLoading"
              class="login-btn">
              <el-icon v-if="isLoading">
                <Loading />
              </el-icon>
              <span v-else>登录</span>
            </el-button>
            <el-button @click="resetForm(ruleFormRef)" class="reset-btn" :disabled="isLoading">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'

import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
import { useCounterStore } from '@/stores/counter'
import { ru } from 'element-plus/es/locales.mjs'

const pinia = useCounterStore();
const router = useRouter();  //页面跳转
const isLoading = ref(false); // 登录按钮加载状态

onMounted(() => {
  GetAccount();
  // 页面加载时自动聚焦到用户名输入框
  setTimeout(() => {
    const usernameInput = document.querySelector('[placeholder="请输入用户账号"]') as HTMLElement;
    usernameInput?.focus();
  }, 100);
})

axios.defaults.baseURL = "http://localhost:5196"  //默认请求路径
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({  //登录参数
  UserName: '',
  UserPwd: '',
  IsRemember: false
})

const GetAccount = () => {  //记住密码的回填
  if (pinia.AccountInfo.UserName !== null) {
    ruleForm.IsRemember = true;
    ruleForm.UserName = pinia.AccountInfo.UserName
    ruleForm.UserPwd = pinia.AccountInfo.UserPwd
  }
  else {
    ruleForm.IsRemember = false;
    ruleForm.UserName = "";
    ruleForm.UserPwd = "";
  }
}

// 参数验证
const rules = reactive<FormRules<typeof ruleForm>>({
  UserName: [
    {
      required: true,
      message: '请输入用户账号',
      trigger: ['blur', 'change']
    },
    {
      min: 1,
      max: 50,
      message: '账号长度应在1到50个字符之间',
      trigger: ['blur', 'change']
    }
  ],
  UserPwd: [
    {
      required: true,
      message: '请输入用户密码',
      trigger: ['blur', 'change']
    },
    {
      min: 1,
      max: 50,
      message: '密码长度应在1到50个字符之间',
      trigger: ['blur', 'change']
    }
  ]
})

// 处理键盘回车键登录
const handleKeyEnter = () => {
  submitForm(ruleFormRef.value);
}

// 登录
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      isLoading.value = true; // 显示加载状态

      axios.get("/api/Users/UserLogin", {
        params: {
          UserName: ruleForm.UserName,
          UserPwd: ruleForm.UserPwd
        }
      }).then(res => {
        console.log(res.data);
        if (res.data.Code == 200) {
          ElMessage.success(res.data.Message);
          console.log(res.data);
          pinia.userinfo.RealName = res.data.Data.RealName; //仓库存用户真实姓名
          pinia.userinfo.RefreshToken = res.data.Data.RefreshToken;  //仓库存redis键
          pinia.userinfo.AccountToken = res.data.Data.AccessToken //存储短期Token
          if (ruleForm.IsRemember == true)  //记住密码
          {
            pinia.AccountInfo.UserName = ruleForm.UserName;
            pinia.AccountInfo.UserPwd = ruleForm.UserPwd;
          }
          else {
            pinia.AccountInfo.UserName = "";
            pinia.AccountInfo.UserPwd = "";
          }
          router.push("/Goods")  //跳转到测试页面
        }
        else {
          ElMessage.error(res.data.Message);
        }
      }).finally(() => {
        isLoading.value = false; // 无论成功失败，都关闭加载状态
      })
    } else {
      console.log('error submit!')
      ElMessage.warning('请检查输入信息是否正确')
    }
  })
}

// 清除数据
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<style scoped>
/* 登录容器样式 - 设置为全屏天蓝色背景 */
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  min-width: 100vw;
  background-color: #87CEEB;
  /* 天蓝色 */
  padding: 20px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1;
}

.login-card {
  width: 100%;
  max-width: 420px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  background-color: white;
  z-index: 2;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.login-header h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 500;
}

.login-form {
  padding: 0 20px;
}

.login-form .el-form-item {
  margin-bottom: 24px;
}

.login-btn {
  width: 60%;
  margin-right: 10px;
}

.reset-btn {
  width: 35%;
}

/* 优化输入框聚焦效果 */
:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px rgba(144, 147, 153, 0.1) !important;
}

/* 优化表单标签样式 */
:deep(.el-form-item__label) {
  font-weight: 500;
}

/* 按钮容器样式 */
.button-container {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 10px;
}

/* 调整按钮样式 */
.login-btn {
  min-width: 120px;
  flex: 1;
  max-width: 150px;
}

.reset-btn {
  min-width: 100px;
  flex: 0.8;
  max-width: 120px;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .button-container {
    flex-direction: column;
  }

  .login-btn,
  .reset-btn {
    max-width: none;
    width: 100%;
  }
}
</style>
